// pages/orderInfo/orderInfo.js
import { getOrderInfoApi, updateOrderApi } from '../../api/order'
// import { getUserInfo } from '../../utils/user'
import { formatDateTime } from '../../utils/util'
import { miniPayApi, getAddressManagementByTypeApi } from '../../api/common'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    orderInfo: {},
    isJihuiState: false,
    showJihuiCarState: false,
    companyAddressInfo: {},
    collapseActive: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData(
      {
        orderId: options.id
      },
      () => {
        this.getOrderInfo()
      }
    )
  },

  /**
   * 展示样品已寄回弹窗
   */
  showJihuiCar() {
    this.setData({
      showJihuiCarState: true
    })
  },

  /**
   * 寄回样品
   */
  jumpAddress() {
    wx.showModal({
      title: '提示',
      content: '您确定要寄回剩余样品吗？您的样品可能已经没有剩余，申请可能会被拒绝，您还要继续吗？',
      complete: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/addressList/addressList?type=2&orderId=${this.data.orderId}`
          })
        }
      }
    })
  },
  /**
   * 拒绝寄回样品
   */
  refuse() {
    wx.showModal({
      title: '拒绝原因',
      content: this.data.orderInfo.refuseReason,
      showCancel: false
    })
  },

  /**
   * 跳转申请发票页面
   */
  jumpApplyForInvoice() {
    wx.navigateTo({
      url: `/pages/applyForInvoice/applyForInvoice?orderId=${this.data.orderId}`
    })
  },

  /**
   * 更新订单状态
   */
  customUpdateOrder() {
    this.updateOrder({
      orderState: 5,
      // specimenBackTime: formatDateTime(new Date().getTime())
      detectCompleteTime: formatDateTime(new Date().getTime())
      // reportUrl: 'www.baidu.com'
    })
  },

  /**
   * 无需物流提交回调
   */
  noCarSubmit(e) {
    this.updateOrder({
      isLogistics: 0,
      noLogisticsNote: e.detail
      // orderState: 3
    })
  },

  /**
   * 提交订单回调
   */
  submitLogisticsSuccess(e) {
    this.updateOrder({
      isLogistics: 1,
      orderState: 3
    })
  },

  /**
   * 获取订单详情
   */
  async getOrderInfo() {
    const [err, info] = await getOrderInfoApi({
      orderId: this.data.orderId
    })
    if (err) return
    info.orderListVO.cancelDuration = (info.orderListVO.cancelDuration ?? 0) * 1000
    this.setData(
      {
        orderInfo: info
      },
      () => {
        // this.customUpdateOrder()
      }
    )
  },

  // 去支付
  async goPay() {
    const [payErr, payInfo] = await miniPayApi({ orderId: this.data.orderInfo.orderListVO.id })
    if (payErr) return
    const { timeStamp = '', nonceStr = '', packAge = '', signType = '', sign = '' } = payInfo
    wx.requestPayment({
      timeStamp: timeStamp,
      nonceStr: nonceStr,
      package: packAge,
      signType: signType,
      paySign: sign,
      success: () => {
        wx.reLaunch({
          url: `/pages/paySuccess/paySuccess?orderId=${this.data.orderInfo.orderListVO.id}`
        })
      },
      fail: () => {
        wx.showToast({
          title: '支付失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 申请退款
   */
  async applyRefund() {
    await this.updateOrder({
      orderState: 98
    })
  },

  /**
   * 取消退款
   */
  async cancelRefund() {
    await this.updateOrder({
      orderState: 2
    })
  },

  /**
   * 修改订单
   */
  async updateOrder(info) {
    const {
      address,
      billStatus,
      orderListVO,
      isLogistics,
      noLogisticsNote,
      remark,
      reportStatus,
      specimenBackTime,
      specimenGoTime
    } = this.data.orderInfo
    const {
      buyerId,
      customerName,
      customerPhone,
      detectCompleteTime,
      id,
      orderNum,
      orderState,
      paymentTime,
      productId
    } = orderListVO
    const [err] = await updateOrderApi({
      address, // 详细地址
      billStatus, // 发票状态 发票状态：1-未申请；2-已申请；3-已开
      buyerId, // 客户id
      customerName, // 下单人姓名
      customerPhone, // 下单人手机号
      detectCompleteTime, // 检测完成时间
      id, // 订单id
      isLogistics, // 是否需要物流：0-否；1-是
      noLogisticsNote, // 无需物流原因
      orderNum, // 订单编号
      orderState, // 订单状态
      paymentTime, // 支付时间
      productId, // 产品id
      receiveAdress: '', // 收货地址
      receiveName: '', // 收货人姓名
      receivePhone: '', // 收货人手机号
      remark, // 订单备注
      reportStatus, // 检测报告状态
      specimenBackTime, // 收样时间
      specimenGoTime, // 发样时间
      updateBy: '', // 更新者
      updateTime: formatDateTime(new Date().getTime()), // 更新时间
      ...info
    })
    if (err) return [err, null]
    this.getOrderInfo()
    return [undefined, 'success']
  },

  /**
   * 获取样品寄件地址
   */
  async getAddressManagementByType() {
    const [err, info] = await getAddressManagementByTypeApi({ type: 1 })
    if (err) return
    this.setData({
      companyAddressInfo: info
    })
  },

  copyAddress() {
    const { contacts, phone, address } = this.data.companyAddressInfo
    const copyText = `${contacts}   ${phone}\n${address}`
    wx.setClipboardData({
      data: copyText,
      success: (res) => {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        })
      },
      fail: (res) => {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.orderId) {
      this.getOrderInfo()
      this.getAddressManagementByType()
    }
  },

  onCollapseChange(e) {
    this.setData({
      collapseActive: e.detail
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
})
